/* 4. 删除/减少书籍 */
const CHECK = require('../myUtil/formatCheck');
const db = require('../../coSqlite3');
const HTM = require('../myUtil/lib').html;

exports.deleteDecreaseBook = function* (req, res) {
    console.log("----------------------4. 删除/减少书籍\n");
    let bID = req.body.bID;
    let bCnt = req.body.bCnt;

    let htm = HTM.divBegin + 3 + HTM.divEnd + '提交的参数有误：';

    if (bID == '') {
        return HTM.begin + htm + '书号不能为空' + HTM.end;
    } else if (bID.length > 30) {
        return HTM.begin + htm + '书号长度不能超过30' + HTM.end;
    }

    if (bCnt == '') {
        return HTM.begin + htm + '数量不能为空' + HTM.end;
    } else if (!CHECK.isNumber(bCnt)) {
        return HTM.begin + htm + '数量必须是数字' + HTM.end;
    } else if (bCnt <= 0) {
        return HTM.begin + htm + '数量必须大于0' + HTM.end;
    }


    htm = HTM.divBegin + 1 + HTM.divEnd;
    try {
        let rows = yield db.execSQL('SELECT count(bid) as count, bID,bTrueCnt,bCnt FROM book WHERE bID = ?', [bID]);

        if (rows[0].count == 0) {
            return HTM.begin + htm + '该书不存在' + HTM.end;
        }
        let row = rows[0];

        if (row.btruecnt < bCnt) {
            let htm = HTM.divBegin + 2 + HTM.divEnd;
            return HTM.begin + htm + '减少的数量大于该书目前在库数量' + HTM.end;
        }
        // console.log((row.btruecnt +":"+ row.bcnt) +":"+ bCnt);
        if (row.btruecnt == bCnt && row.bcnt == bCnt) {
            // yield db.execSQL("PRAGMA foreign_keys = 1");
            yield db.execSQL('delete from book where bid=?', [bID]);
        } else {
            yield db.execSQL('UPDATE book SET bCnt = bCnt - ?, bTrueCnt = bTrueCnt - ?  WHERE bID = ?', [bCnt, bCnt, bID]);
        }
    } catch (err) {
        htm = HTM.divBegin + 3 + HTM.divEnd + "数据库执行失败:";
        return HTM.begin + htm + err + HTM.end;
    }
    
    htm = HTM.divBegin + 0 + HTM.divEnd;
    return HTM.begin + htm + '成功' + HTM.end;
}